import re
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from utils.db import db
import json

# Create your views here.


def showuseraudit(request):

    sql = "select c.id,c.name,c.tmoney,c.company_name,c.status from customer as c left join reg_form as rf on c.refromid=rf.id left join customer_manager as cm on cm.id=c.manager_id"

    res = db.get_all(sql)

    return JsonResponse({"code":200,"list":res})

# 审核列表接口
def audit(request):

    import time
    # 获取参数
    data = json.loads(request.body)
    print(data)
    time = int(time.time())
    sql = "select * from customer where id=%d"%(int(data['id']))
    customer = db.get_one(sql)

    # 更新customer表，状态，审核人，审核时间
    sql1 =  "update customer set status=%d,audit_time=%d,audit_name='zs' where id=%d"%(int(data['is_agree']),time,int(data['id']))
    db.update(sql1)
    db.commit()

    # 更改来源表
    sql2 = "select id,tcount from reg_form where id=%d"%(int(customer['refromid']))

    regform = db.get_one(sql2)

    number = int(regform['tcount'])+1

    sql3 = 'update reg_form set tcount=%d where id=%d'%(int(number),int(customer['refromid']))
    db.update(sql3)
    db.commit()

    # 更新客户经理中的总金额
    sql4 = "select * from customer_manager where id=%d"%(int(customer['manager_id']))
    manager = db.get_one(sql4)

    number = int(manager['tmoney'])+int(customer['tmoney'])

    sql5 = " update customer_manager set tmoney=%d where id=%d " % (int(number),int(customer['manager_id']))

    db.update(sql5)
    db.commit()

    return JsonResponse({"code":200})


def getmes(request):

    sql = " select name,tcount from reg_form "
    res = db.get_all(sql)

    list = [{'value':i['tcount'],'name':i['name']} for i in res]
    return JsonResponse({"code":200,"list":list})


def getcustomer(request):

    sql = 'select * from customer'
    res = db.get_all(sql)
    return JsonResponse({"code":200,'list':res})


from dwebsocket.decorators import accept_websocket
websocketlist=[]

@accept_websocket
def websocket_conn(request):
    if request.is_websocket:
        websocketlist.append(request.websocket)
        
    for message in request.websocket:
            break 

#发送消息
def sendmes():
    sql = "select name from customer"
    res = db.get_all(sql)

    if websocketlist:
        for i in websocketlist:
            mes=[]
            for j in res:
                mes.append({"name":j['name']})
            b1 = json.dumps(mes,ensure_ascii=False).encode('utf-8')
            i.send(b1)
    return HttpResponse('ok')


from apscheduler.schedulers.background import BackgroundScheduler

def test(request):
    scheduler = BackgroundScheduler()
    # 添加调度任务
    # 调度方法为 timedTask，触发器选择 interval(间隔性)，间隔时长为 2 秒
    scheduler.add_job(sendmes, 'interval', seconds=2)
    # 启动调度任务
    scheduler.start()
    return HttpResponse('ok')


import requests
import json
import redis
import time

def sendmes1(request):
    while 1:
        time.sleep(1)
        data = request.GET
        audit_id = int(data['audit_id'])
        #通过审核人去redis中取id
        r = redis.Redis()
        key = 'audit%d'%(int(audit_id))
        id = str(r.rpop(key),encoding='utf8')
       
        mes = requests.get('http://localhost:5000/getnews?id='+str(id))
      
        news = json.loads(mes.text)
    
        if auditlist:
            for k,v in auditlist.items():
                if int(k) == 2:
                    b1 = json.dumps(news,ensure_ascii=False).encode('utf-8')
                    v.send(b1)
        return HttpResponse("ok")


#定义审核人list
auditlist={}
#websocket scorechange1
@accept_websocket
def web_conn(request,userid):
    if request.is_websocket:
        auditlist[userid]=request.websocket
        
    for message in request.websocket:
            break 
import time
def score_change(request):
    while 1:
        time.sleep(3)
        userid = request.GET.get('userid')
        sql = "select sum(score) as tscore,date(ctime) as addtime from  score_record where userid=%d and type=1 group by date(ctime)"%(int(userid))
        res = db.get_all(sql)
       
        list1 = [float(i['tscore']) for i in res]
        list2 = [str(i['addtime']) for i in res]
        list=[]
        list.append(list1)
        list.append(list2)
        if auditlist:
            mes = json.dumps(list,ensure_ascii=False)
            auditlist['scorechange'+str(userid)].send(mes)








